package m.fun.action;

import m.base.action.BaseAction;
import m.base.action.StoreInfoAction;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.*;
import m.fun.model.GoodsOffer;
import m.fun.model.OfferDetail;
import m.fun.service.GoodsOfferService;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Button;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.attr.Size;
import m.html.form.*;
import m.html.list.*;
import m.store.model.StoreGoods;
import m.store.model.StoreType;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.model.StatusModel;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@ActionMeta(name = "fun/goodsOffer")
public class GoodsOfferAction extends BaseAction {
    private GoodsOffer model;
    private List<StoreGoods> goodsList;
    private void verifyFunc() throws Exception {
        if(!LevelUtil.offerFunc()){
            throw new MException(this.getClass(),"当前商户未开通报价单功能")
                .setRedirect(LevelUtil.toErrorPage("当前商户未开通报价单功能",false));
        }
    }
    @RequestMeta(params = {"oid"})
    public JSONMessage getGoods(String oid) throws Exception {
        model=ModelQueryList.getModel(GoodsOffer.class,oid,"goods.*");
        return new JSONMessage(0).push("goods",model.getGoods());
    }
    @RequestMeta(logTitle = "商品报价",logDescription = "添加商品报价")
    public JSONMessage doAddGoods() throws Exception {
        getService(GoodsOfferService.class).addStoreGoods(PowerUtil.getSessionUser(true),goodsList);
        return new JSONMessage(0,"添加成功");
    }
    /*
     * 编辑商品报价
     */
    public VueResult toAdd() throws Exception {
        ModelForm form = new ModelForm("批量添加商品");
        form.addItem(
            FormInput.selectManyModel("添加商品","list","goodsList","'"+actionUrl("selectStoreGoods")+"'",Element.tag("div").A("v-for","item in list.goodsList").E("{{item.name}}").toString()).setSpan(3)
        )
        .addData("list",new JSONMessage().push("goodsList",new ArrayList<>()))
        .addButton(
            FormButton.pri("确定添加","doAddGoods")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doAddGoods",actionUrl("doAddGoods"),"{goodsList:this.list.goodsList}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form)
                .addForm(new CustomForm(Element.tag("a-alert").A("message","若没有找到商品，请确认商品是否设置了商品分类和报价。")));
    }
    @RequestMeta(logTitle = "商品报价",logDescription = "保存商品报价信息")
    public JSONMessage doSave() throws MException {
        ModelUpdateUtil.updateModel(model,"color","title","indexTxt","priceTxt");
        return new JSONMessage(0,"修改成功");
    }
    @RequestMeta(logTitle = "商品报价信息",logDescription = "删除商品报价信息")
    public JSONMessage doDelete() throws MException, SQLException {
        if(!ModelQueryList.getModelList(OfferDetail.class,new String[]{"oid"},new QueryPage(0,1),
                QueryCondition.eq("goodsOffer.oid",model.getOid())).isEmpty()){
            throw new MException(this.getClass(),"已被报价单关联，不能删除！");
        }
        ModelUpdateUtil.deleteModel(model);
        return new JSONMessage(0,"删除成功");
    }
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","goods.name");
            PowerUtil.verifyUserData(model.getUser().getOid());
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        ModelForm form = new ModelForm("商品报价",2);
        form.addItem(
            FormHtml.ins("颜色",
                Element.tag("div").E(
                    Element.tag("a-tag").A("v-for","item in dictOptions('color')")
                        .A(":color","model.color==item.value?item.value:item.label")
                        .A("@click","model.color=item.value").E("颜色"),
                    new Button(Size.SMALL,ButtonType.LINK).E("清除颜色").A("v-if","model.color").A("@click","model.color='';")
                )
            ).setSpan(2),
            FormInput.input("展示名称","model.title").setPlaceholder("请输入展示名称").setSpan(2),
            FormInput.select("展示标识", "model.indexTxt", "m.fun.model.GoodsOffer!indexTxt"),
            FormInput.input("展示价格", "model.priceTxt").setPlaceholder("请输入价格展示")
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("保存","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
    }
    public VueResult selectStoreGoods() throws Exception {
        String selected=getParamsValue("selected","");
        VueListResult result=getVueListResult("选择商品",StoreGoods.class,actionUrl("selectStoreGoods"));
        result.setDescribe("<a-alert :message=\"'已选择'+sumSelected(item=>1)+'种商品。'\" style=\"margin-bottom:10px;\" />");
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setSelection("oid", false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
//        result.addCol(toTextColumn("商品类型", "typeName", 100, true));
        result.addCol(toTextColumn("商品分类", "storeType.oid", 100, true).setDictType(StoreType.class,PowerUtil.getSessionStoreOid()));
//        result.addCol(toTextColumn("厂商", "factoryName", 100, true));
        result.addCol(toLinkColumn("名称", "name", 250, true,
            new ListEvent(actionUrl(StoreInfoAction.class,"toView"), EventType.MODAL,600)
                .addParam("model.oid","oid")
        ));
        result.addCol(toNumberColumn("报价","offerPrice",100,true));
        result.addCol(toNumberColumn("均价", "surplusPrice", 100, true).setGroupTitle("剩余"));
        result.addCol(toIntegerColumn("数量", "surplusNum", 100, true).setGroupTitle("剩余"));
        result.addCol(toNumberColumn("金额", "surplusAmount", 100, true).setGroupTitle("剩余"));
        result.addButton(ListButton.back("选择", ButtonType.PRIMARY).addParam("",""));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.eq("status", StatusModel.Status_Enable));
        result.addCondition(QueryCondition.eq("property", StoreGoods.Property_Goods));
        result.addCondition(QueryCondition.notEmpty("storeType.oid"));
        result.addCondition(QueryCondition.not(
           QueryCondition.in("oid",
               ModelQueryList.instance(GoodsOffer.class,new String[]{"goods.oid"},null,
                   QueryCondition.eq("user.oid",PowerUtil.getSessionUserOid())
               )
           )
        ));
        return result;
    }
    /*
     * 商品报价列表
     */
    public VueResult editList() throws Exception {
        verifyFunc();
        VueListResult result=getVueListResult("商品报价",GoodsOffer.class,actionUrl("editList"));
        result.setSubTitle("修改商品报价信息后，会立即更新所关联的报价单。");
        result.setFunction(true,false);
        result.setHeight(-1);
        result.addQueryFields("color");
        result.setSelection("oid",false);
        result.addCol(toIndexColumn());
//        result.addCol(toTextColumn("商品类型", "goods.typeName", 130, true)
//            .setFieldExpression("concat(#{goods.type.parent.name},' - ',#{goods.typeName})"));
//        result.addCol(toTextColumn("厂商", "goods.factoryName", 100, true));
        result.addCol(toTextColumn("商品分类", "goods.storeType.oid", 100, true).setDictType(StoreType.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("商品名称", "goods.name", 250, true));
        result.addCol(toNumberColumn("报价", "goods.offerPrice", 100, true).setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "goods.surplusNum", 100, true).setGroupTitle("剩余"));
        result.addCol(toNumberColumn("金额", "goods.surplusAmount", 100, true).setGroupTitle("剩余"));
        result.addCol(toNumberColumn("均价", "goods.surplusPrice", 100, true).setGroupTitle("剩余"));
        result.addCol(toTextColumn("展示名称", "title", 250, true).addClassName("record.color","'text-'+dict('color',record.color)"));
        result.addCol(toTextColumn("展示标识", "indexTxt", 100, true).setDictType("m.fun.model.GoodsOffer!indexTxt"));
        result.addCol(toTextColumn("展示价格", "priceTxt", 100, true));
        result.addCol(toSpaceColumn("操作", 130,
            ListButton.drawer("修改", ButtonType.PRIMARY,actionUrl("toEdit"),600, SuccessMethod.REFRESH)
                .addParam("model.oid","oid"),
            ListButton.ajax("删除", ButtonType.WARN,actionUrl("doDelete"), SuccessMethod.REFRESH)
                .addParam("model.oid","oid").setConfirm("确定要删除吗？")
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.modal("添加", ButtonType.PRIMARY,actionUrl("toAdd"),600, SuccessMethod.REFRESH),
            ListButton.ajax("删除", ButtonType.WARN,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("确定要删除吗？")
        );
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("user.oid", PowerUtil.getSessionUserOid()));
        result.addOrder(
            QueryOrder.asc("goods.storeType.sort"),
            QueryOrder.asc("title")
        );
        return result;
    }

    public GoodsOffer getModel() {
        return model;
    }

    public void setModel(GoodsOffer model) {
        this.model = model;
    }

    public List<StoreGoods> getGoodsList() {
        return goodsList;
    }

    public void setGoodsList(List<StoreGoods> goodsList) {
        this.goodsList = goodsList;
    }
}
